package com.cloudkinto.controller.order;

import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.entity.OrderOutputPackageDetailDo;
import com.cloudkinto.service.order.OrderTiktokService;
import com.cloudkinto.service.order.impl.OrderTiktokServiceImpl;
import com.cloudkinto.service.order.vo.Export2ShipOrderReq;
import com.cloudkinto.service.order.vo.shopify.OrderShopifyRes;
import com.cloudkinto.service.order.vo.tiktok.OrderIdRequest;
import com.cloudkinto.service.order.vo.tiktok.OrderTiktokQueryBo;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import com.cloudkinto.service.user.vo.AuthResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import tiktokshop.open.sdk_java.model.Authorization.V202309.GetAuthorizedShopsResponse;
import tiktokshop.open.sdk_java.model.Order.V202309.GetOrderListResponse;
import tiktokshop.open.sdk_java.model.Order.V202309.GetOrderListResponseDataOrders;
import tiktokshop.open.sdk_java.model.Product.V202502.SearchProductsResponse;

import java.util.*;
import java.util.concurrent.TimeUnit;


@Api(tags = "Tiktok订单模块")
@RestController
@RequestMapping("/api/logistics/tiktok")
public class OrderTiktokController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(OrderTiktokServiceImpl.class);
    @Autowired
    private OrderTiktokService service;

    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation("获取授权url")
    @GetMapping("/url")
    public String
    getAuthUrl() {
        return service.generateAuthUrl();
    }

    @ApiOperation("回调函数")
    @GetMapping("/callback")
    public SingleResult<AuthResponse> handleCallback(@RequestParam String code) throws Exception {
        return service.getAccessToken(code);
    }

 /*   @GetMapping("/shopList")
    @ApiOperation(value = "获取店铺", notes = "获取店铺")
    public SingleResult shopListFromPlantForm() {
           *//* Long companyId2 = getCompanyId();
            //todo 待处理
            if(companyId2==null)
            {
                companyId2=null;
            }*//*
        Long companyId2 = null;
        return SingleResult.success(service.shopListFromPlantForm(*//*getCurrentUserId()*//*null, companyId2));
    }*/

    @UserSessionRequired
    @GetMapping("/shopList")
    @ApiOperation(value = "获取店铺", notes = "获取店铺")
    public SingleResult shopListFromPlantForm() {

        return SingleResult.success(service.shopListFromPlantForm(getCompanyId()));
    }


//    @ApiOperation("刷新token")
//    @GetMapping("/refresh")
//    public SingleResult<AuthResponse> handleRefresh(@RequestParam String refreshToken,Long shopId) throws Exception {
//        return service.refreshAccessToken(refreshToken);
//    }


    /* @ApiOperation("搜索商品")
     @GetMapping("/searchProduct")
     public SingleResult<SearchProductsResponse> searchProducts(String accessToken, String shopCipher, String appKey, int pageNumber, int pageSize) throws ApiException {
         return SingleResult.success(authService.searchProducts(accessToken, shopCipher,appKey,pageNumber,pageSize));
     }*/
    @ApiOperation("搜索商品")
    @GetMapping("/searchProduct")
    public SingleResult<SearchProductsResponse> searchProducts(Integer shopId, int pageNumber, int pageSize) {
        return SingleResult.success(service.searchProducts(shopId, pageNumber, pageSize));
    }

    @ApiOperation("授权商店")
    @GetMapping("/authorizeShop")
    public SingleResult<GetAuthorizedShopsResponse> authorizeShop(String accessToken) throws Exception {
        return SingleResult.success(service.authorizeShop(accessToken));
    }

    @UserSessionRequired
    @ApiOperation("获取订单")
    @PostMapping("/getOrder")
    public SingleResult<List<GetOrderListResponseDataOrders>> getOrder(String accessToken, String shopCipher, Long shopId, String startDate, String endDate) throws Exception {
        Long companyId = getCompanyId();
        return SingleResult.success(service.getOrder(accessToken, shopCipher, shopId, startDate, endDate, companyId));
    }
    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = OrderShopifyRes.class))
    public PageResult listPage(OrderTiktokQueryBo bo) {
        bo.setCompanyId(getCompanyId());
        return service.getListPage(bo);
    }


    @PostMapping("markSendOut")
    @UserSessionRequired
    @ApiOperation(value = "标记发货", notes = "抖音订单发货")
    public SingleResult marksendOut(@RequestBody List<Long> ids) {
        Long currentUserId = getCurrentUserId();
        List<String> orderIds=service.getOrderIds(ids);
        return SingleResult.success(service.markSendOut(orderIds ,  currentUserId));
    }

    @UserSessionRequired
    @ApiOperation(value = "标记包裹为已发货", notes = "抖音订单包裹标记为已发货")
    @PostMapping("/markPackageAsShipped")
    public SingleResult markPackageAsShipped(@RequestParam List<String> orderIds) {
        //Long companyId = getCompanyId();
     //   List<String> orderIds = request.getOrderId();
        List<Map<String, List<OrderOutputPackageDetailDo>>> orderRequstsList = new ArrayList<>();

        for (String orderId : orderIds) {
            List<OrderOutputPackageDetailDo> packageDetailDos = new ArrayList<>();
            Map<String, List<OrderOutputPackageDetailDo>> orderRequests = new HashMap<>();
            orderRequests.put(orderId, packageDetailDos);
            orderRequstsList.add(orderRequests);
        }

        return SingleResult.success(service.markPackageAsShipped(orderRequstsList));
    }


    @UserSessionRequired
    @PostMapping("sendOut")
    @ApiOperation(value = "发货", notes = "发货")
    public SingleResult sendOut(@RequestBody Export2ShipOrderReq req) throws Exception {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        // if (req.getIsSolo() == 0) {
        return service.sendOut(req.getOrderids(), userId, companyId, false);
        // } else {
        //     return service.sendOutNopackage(req.getOrderids()[0], userId, companyId);
        // }

    }

    @UserSessionRequired
    @PostMapping("sendOutMatch")
    @ApiOperation(value = "确认发货发货", notes = "确认发货发货")
    public SingleResult sendOutMatch(@RequestBody List<OrderOutputAddReq> orderOutputAddReqList) throws Exception {
        Long userId = getCurrentUserId();
        return service.sendOutMatch(orderOutputAddReqList, userId, false);
    }


    /**
     * 获取指定配送选项下的物流服务商列表
     */
    @ApiOperation(value = "获取物流供应商", notes = "获取物流供应商")
    @GetMapping("/shipping-providers/{deliveryOptionId}")
    public SingleResult getShippingProviders(
            @PathVariable String deliveryOptionId,
            String accessToken, String shopCipher) {

        return SingleResult.success(service.getShippingProviders(deliveryOptionId, accessToken, shopCipher));
    }

    /**
     * 获取订单的物流跟踪信息
     */
    @GetMapping("/orders/{orderId}/tracking")
    public SingleResult getTrackingInfo(
            @PathVariable String orderId) {

        return SingleResult.success(service.getTrackingInfo(orderId));
    }

    @GetMapping("/sync")
    @UserSessionRequired
    @ApiOperation(value = "同步订单")
    public SingleResult sync(Long shopId, String startDate, String endDate) throws Exception {
          Long companyId = getCompanyId();
        return service.sync(shopId, startDate, endDate, companyId);
    }




    //每隔一分钟秒后定时执行
     // @Scheduled(fixedDelay = 1000*20)
    //每天下午5点05执行
   // @Scheduled(cron = "0 0 0 * * ?")
    @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨 0 点执行
    public void refreshTokenIfExpiredForAllShops() {
        service.fixedTokenRefresh();
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    public SingleResult detail(@PathVariable("id") String id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

    @UserSessionRequired
    @GetMapping("/detailOrder/{orderId}")
    @ApiOperation(value = "根据id查看订单详情", notes = "根据id查看订单详情")
    public SingleResult detailOrder(@PathVariable("orderId") String orderId) {
        return SingleResult.success("查询成功", service.detailOrder(orderId));
    }


}
